import Vue from 'vue';

function pruneCacheEntry(cache, key, current) {
    const cached = cache[key];
    if (cached && (!current || cached.tag !== current.tag)) {
        cached.componentInstance.$destroy();
    }
    delete cache[key];
}


export default function (navigation) {
    const navigationComponent = {
        name: 'navigation',
        abstract: true,
        render() {
            const slot = this.$slots.default || this.$children;
            const vnode = slot[0];
            const componentOptions = vnode && vnode.componentOptions;
            if (componentOptions) {
                const {cache} = this;
                const {currentRouteId} = navigation;
                const key = vnode.key == null ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key;
                const id = currentRouteId + ',' + key;
                if (cache[id]) {
                    vnode.componentInstance = cache[id].componentInstance;
                    console.log('取缓存', id);
                } else {
                    cache[id] = vnode;
                    console.log('缓存', id);
                }

                vnode.data.keepAlive = true;
            }
            console.info('---over---');
            return vnode || (slot && slot[0]);
        },
        created() {
            this.cache = Object.create(null);
            window.cache = this.cache;
            window.t = this;
        },
        destroyed() {
            for (const key in this.cache) {
                pruneCacheEntry(this.cache, key);
            }
        },
        watch: {
            $route() {
                for (let idstr in this.cache) {
                    const [name, key] = idstr.split(',');
                    navigation.history.includes(name + ',' + key) || pruneCacheEntry(this.cache, idstr);
                }
            }
        }
    };
    console.log('注册navigation');
    Vue.component('Navigation', navigationComponent);
}
